//
//  XiaoSiRenLe.swift
//  sheyingzu
//
//  Created by Penlon Kim on 2024/6/6.
//

import Foundation
import Reachability

// 定义网络状态枚举
@objc public enum DzblJpsAfge: Int {
    case RchSvi
    case MlqkNwdvh
    case WcytPdzsm
    case YubqTkg
}

// 网络状态监控工具类
@objcMembers
class XiaoSiRenLe: NSObject {
    
    @objc public static let UniqueInstanceIdentifier = XiaoSiRenLe()
    
    typealias NetworkStatusChangeHandler = (DzblJpsAfge) -> Void
    /// 网络状态变化时触发的闭包
    private var NetworkStatusChangeCallback: NetworkStatusChangeHandler?
    
    /// 监听网络状态变化
    @objc public func StartMonitoringNetworkStatus(by ChangeHandler: @escaping NetworkStatusChangeHandler, look: Bool = false) {
        NetworkStatusChangeCallback = ChangeHandler
        if look {
            Hjsuwondkasd()
        }
    }
    
    // Reachability实例
    private var ReachabilityInstance: Reachability?

    override init() {
        super.init()
        InitializeReachability()
    }

    // 设置Reachability监听
    private func InitializeReachability() {
        ReachabilityInstance = try? Reachability()
        
        // 网络可达时的处理
        ReachabilityInstance?.whenReachable = { [weak self] reachability in
            guard let weakSelf = self else { return }
            let networkStatus: DzblJpsAfge = reachability.connection == .wifi ? .YubqTkg : .WcytPdzsm
            weakSelf.NetworkStatusChangeCallback?(networkStatus) // 通知网络状态改变
            print("网络状态改变为 >>> \(networkStatus.rawValue)")
        }
        
        // 网络不可达时的处理
        ReachabilityInstance?.whenUnreachable = { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.NetworkStatusChangeCallback?(.MlqkNwdvh) // 通知网络状态改变
            print("网络状态改变为 >>> \(DzblJpsAfge.MlqkNwdvh.rawValue)")
        }
    }

    /// 开始监听网络状态
    @objc public func BeginMonitoringNetworkStatus() {
        do {
            try ReachabilityInstance?.startNotifier()
            print("开始监听网络状态")
        } catch {
            print("无法启动网络状态监听")
        }
    }

    /// 停止监听网络状态
    @objc public func StopMonitoringNetworkStatus() {
        ReachabilityInstance?.stopNotifier()
        print("停止监听网络状态")
    }
    
    /// 主动通知当前网络状态
    @objc private func Hjsuwondkasd() {
        guard let reachability = ReachabilityInstance else {
            NetworkStatusChangeCallback?(.RchSvi)
            return
        }
        
        let status: DzblJpsAfge
        switch reachability.connection {
        case .wifi:
            status = .YubqTkg
        case .cellular:
            status = .WcytPdzsm
        case .unavailable:
            status = .MlqkNwdvh
        }
        
        NetworkStatusChangeCallback?(status)
        print("当前网络状态 >>> \(status.rawValue)")
    }
    
}
